<template>
  <OperationBar class="py-5" @refresh-list="() => getTableList()" />
  <div class="flex flex-col justify-between bg-white table-content">
    <el-table
      v-loading="loading"
      class="basic-table"
      height="100%"
      :data="dataSource"
      :row-class-name="tableRowClass"
      row-key="id"
      @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="name"
        show-overflow-tooltip
        label="节点名称"
        min-width="77"
      >
        <template #default="{ row }">
          <span class="text-[#3478F6]">{{ row.name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="group_name"
        show-overflow-tooltip
        label="所属分组"
        min-width="84"
      >
        <template #default="{ row }">
          <span>{{ row.group_name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="ips"
        show-overflow-tooltip
        label="节点IP"
        min-width="88"
      >
        <template #default="{ row }">
          <span>{{ row.ips.join(',') || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="platform"
        show-overflow-tooltip
        label="系统信息"
        min-width="124"
      >
        <template #default="{ row }">
          <span>{{ row.platform || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="kernel_version"
        show-overflow-tooltip
        label="内核信息"
        min-width="130"
      >
        <template #default="{ row }">
          <span>{{ row.kernel_version || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="node_status"
        show-overflow-tooltip
        label="节点状态"
        min-width="77"
      >
        <template #default="{ row }">
          <span :style="{ color: getStatusStyle(row.node_status) }">{{
            getNodeStatus(row) || '-'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="tcc_status"
        show-overflow-tooltip
        label="TCC状态"
        min-width="90"
      >
        <template #default="{ row }">
          <span :style="{ color: getStatusStyle(row.tcc_status) }">{{
            getTccStatus(row.tcc_status) || '-'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="bbr_status"
        show-overflow-tooltip
        label="内核自带BBR"
        min-width="98"
      >
        <template #default="{ row }">
          <span :style="{ color: getStatusStyle(row.bbr_status) }">{{
            getBbrStatus(row.bbr_status) || '-'
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="tcc_version"
        show-overflow-tooltip
        label="TCC版本"
        min-width="106"
      >
        <template #default="{ row }">
          <div class="box">
            <a class="tooltip" data-msg="更新" v-if="isNewVersion(row)">{{
              row.tcc_version
            }}</a>
            <span class="text-[#333]" v-else>{{ row.tcc_version }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="last_reported_at"
        label="最近上报日期"
        min-width="154"
      >
        <template #default="{ row }">
          <!-- mock 数据需要转换 所以除以1000 -->
          {{ formatUnix(Number(row.last_login_at / 1000)) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="132">
        <template #default="{ row }">
          <div class="flex items-center justify-around">
            <el-link
              class="common-btn"
              :underline="false"
              type="primary"
              color="#3478F6"
              @click="handleCommand('edit', row)"
              >编辑</el-link
            >
            <el-link
              class="common-btn"
              :underline="false"
              type="primary"
              @click="handleCommand('detail', row)"
              >详情</el-link
            >
            <!-- 
              <el-link
              class="common-btn"
              :underline="false"
              type="primary"
              @click="handleCommand('editor_dialog', row)"
              >编辑(dialog)</el-link
            >
             -->
            <el-link
              class="common-btn"
              :underline="false"
              type="primary"
              @click="handleCommand('more', row)"
            >
              <el-dropdown trigger="click">
                <el-button type="primary" link class="common-btn">
                  更多
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu class="w-[128px]">
                    <el-dropdown-item
                      class="pl-6 text-[#F15443]"
                      @click="handleCommand('delete', row)"
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown></el-link
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <BasicPagination
      ref="paginationRef"
      :total="total"
      :disabled="loading"
      @change="getTableList"
    >
    </BasicPagination>

    <DetailDialog
      :visible="detailVisible"
      :id="detailId"
      @close-dialog="() => (detailVisible = false)"
      @refresh-table="() => getTableList()"
    />
    <NodeEditorDialog
      :visible="editVisible"
      :record="editState"
      @close-dialog="() => (editVisible = false)"
      @refresh-table="() => getTableList()"
    />
  </div>
</template>
<script lang="ts" setup>
import { get, isFunction } from 'lodash-es'
import OperationBar from '../components/OperationBar.vue'
import { formatUnix } from '@/utils'
import DetailDialog from './DetailDialog.vue'
import { ElMessageBox, ElNotification } from 'element-plus'
import NodeEditorDialog from './NodeEditorDialog.vue'
import type { NodeData } from '@/apis/model/node'
import { omit } from 'lodash-es'
import {
  state,
  TCC_STATUS,
  NODE_STATUS,
  BBR_STATUS,
  multipleSelection,
  STATUS_STYLE
} from '../state'
const router = useRouter()
const paginationRef = ref()
const loading = ref<boolean>(false)
const dataSource = ref<NodeData[]>([])
const total = ref(0)
const editVisible = ref(false)
const editState = reactive<{ id: string; group_id: string; name: string }>({
  id: '',
  name: '',
  group_id: ''
})
const detailVisible = ref(false)
const detailId = ref('')
const editorState = reactive<CommonDialog<any>>({
  visible: false,
  record: undefined,
  loading: false
})
const rowId = ref('')
//某一行row样式
const tableRowClass = row => {
  if (rowId.value === row.id) return 'current-row'
  return ''
}
//某一行点击事件
const handleRowClick = row => {
  rowId.value = row.id
}
//勾选事件
const handleSelectionChange = (row: NodeData[]) => {
  multipleSelection.value = row.map(item => (item.id as string) ?? '')
}
//是否是最新版本
const isNewVersion = computed(
  () => (row: NodeData) => row.tcc_version === row.latest_tcc_version
)
//获取状态样式
const getStatusStyle = computed(() => (status: number) => STATUS_STYLE[status])
/**
 * 获取节点状态
 */
const getNodeStatus = computed(
  () => (row: NodeData) =>
    row.node_status && row.node_status === 1
      ? NODE_STATUS[row.node_status]
      : NODE_STATUS[row.node_status] + row.offline_days + '天'
)
/**
 * 获取tcc状态
 */
const getTccStatus = computed(
  () => (tcc_status: number) => TCC_STATUS[tcc_status]
)
/**
 * 获取bbr状态
 */
const getBbrStatus = computed(
  () => (bbr_status: number) => BBR_STATUS[bbr_status]
)
type ICommand =
  | 'detail'
  | 'edit'
  | 'delete'
  | 'create'
  | 'create_dialog'
  | 'editor_dialog'
  | 'more'
const handleCommand = (command: ICommand, record?: any) => {
  const actions: Record<ICommand, () => void> = {
    create: (): void => {
      router.push({ name: 'AdminEditorExample' })
    },
    edit: (): void => {
      editVisible.value = true
      editState.group_id = record.group_id
      editState.id = record.id
      editState.name = record.name
    },
    detail: (): void => {
      detailVisible.value = true
      detailId.value = record.id
    },
    delete: (): void => {
      ElMessageBox.confirm('确定要删除该节点的TCC吗？', '删除TCC', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        customClass: 'basic-message-box'
      }).then(() => {
        delete_single_node({ id: record.id })
          .then(() => {
            ElNotification.success({
              title: '成功',
              message: '删除成功'
            })
          })
          .finally(() => {
            getTableList()
          })
      })
    },
    create_dialog: (): void => {
      editorState.record = undefined
      editorState.visible = true
      editorState.loading = false
    },
    editor_dialog: (): void => {
      editorState.record = record
      editorState.visible = true
      editorState.loading = false
    },
    more: (): void => {}
  }
  if (isFunction(get(actions, command))) {
    actions[command]()
  }
}
const getTableList = (params = {}) => {
  const query = {
    ...omit({ ...state, ...params }, ['page'])
  }
  loading.value = true
  node_list({ ...query })
    .then(res => {
      dataSource.value = res?.list ?? []
      total.value = +res?.total ?? 0
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 200)
    })
}
defineExpose({ getTableList })
</script>
<style lang="scss">
:deep(.current-row) {
  color: #333;
  background-color: #f9faff;
}
</style>
<style lang="scss" scoped>
.table-content {
  height: calc(100% - 125px);
}
:deep(.current-row) {
  color: #333;
  background-color: #f9faff;
}
.box {
  margin: 10px 0;
}

.tooltip {
  position: relative;
  font-size: 12px;
  cursor: pointer;
  color: #333333;
  font-weight: 500;
  letter-spacing: 0;
  line-height: 12px;
}
.tooltip::after {
  word-break: keep-all;
  white-space: nowrap;
  content: attr(data-msg);
  position: absolute;
  padding: 3px 6px;
  display: block;
  color: #2d61ee;
  border: 1px solid #2d61ee;
  background: #eaf0ff;
  border-radius: 9px 9px 9px 0px;
  font-size: 10px;
  line-height: 10px;
  top: -14px;
  right: -214%;
  transform: translateX(-50%);
}
</style>
